#include "demoprotocol.h"

DEMOProtocol::DEMOProtocol ( QObject* parent ) : QQtProtocol ( parent )
{

}

DEMOProtocol* DEMOSerialPort ( QObject* parent )
{
    static DEMOProtocol* p0 = nullptr;
    static QQtSerialPort* s0 = NULL;

    if ( !s0 && !p0 )
    {
        p0 = new DEMOProtocol ( parent );
        s0 = new QQtSerialPort ( parent );
        s0->setPortName ( "/dev/ttyUSB0" );
        s0->setBaudRate ( QSerialPort::Baud9600 );
        s0->setDataBits ( QSerialPort::Data8 );
        s0->setFlowControl ( QSerialPort::NoFlowControl );
        s0->setStopBits ( QSerialPort::TwoStop );
        s0->installProtocol ( p0 );
    }

    return p0;
}

DEMOMessage::DEMOMessage ( QObject* parent )
{
    startBytes = 0x2B3C;
    stopBytes = 0x4D5E;
    addressBytes = 0x01020304;

}

quint8& DEMOMessage::productBytes() { return mProductBytes; }

quint8& DEMOMessage::commandBytes() { return mCommandBytes; }

quint16& DEMOMessage::paramBytes() {return mParamBytes;}

void DEMOMessage::parser ( const QByteArray& pkg )
{
    QByteArray l = pkg;
    l >> startBytes;
    l >> addressBytes;
    l >> mProductBytes;
    l >> mCommandBytes;
    l >> mParamBytes;
    l >> stopBytes;
}

void DEMOMessage::packer ( QByteArray& l ) const
{
    l << startBytes;
    l << addressBytes;
    l << mProductBytes;
    l << mCommandBytes;
    l << mParamBytes;
    l << stopBytes;
}

QDebug& operator<< ( QDebug& dbg, const DEMOMessage& msg )
{
    dbg.nospace() << "{"
                  << hex << msg.productBytes() << "|"
                  << hex << msg.commandBytes() << "|"
                  << hex << msg.paramBytes()
                  << "}";
    return dbg.space();
}
